<template>
  <div class="page page__syssetting clearBoth">
    <div
      v-for="(item, index) in navlist"
      :key="index"
      @click="showForm(item)"
      class="entry_items left pointer"
    >
      <i :class="`icon jeicon ${item.icon}`" />
      <div class="text">
        <p class="title">
          {{ item.label }}
        </p>
        <p>{{ item.text }}</p>
      </div>
    </div>
    <el-dialog
      :visible.sync="showDialog"
      :modal-append-to-body="false"
      :show-close="false"
      :modal="false"
      top="0"
      fullscreen
      class="sys_setting_dialog"
    >
      <form-page
        ref="formPage"
        :navlist="navlist"
        :active="active"
        :formdata="formdata"
        :dictlist="dictlist"
        @hideDialog="hideDialog"
        @submit="submit"
      />
    </el-dialog>
  </div>
</template>

<script>
import { setTimeout } from 'timers';
import { loadSysVariables, getDicItemByCode, writeSysVariables } from './actions/api.js';
import formPage from './modules/form';
import form from './form';

export default {
  name: 'SystemSetting',
  components: { formPage },
  data() {
    return {
      showDialog: false,
      active: {},
      navlist: [
        {
          value: 'jmsj',
          label: '页面设置',
          icon: 'jeicon-configuration',
          text: '页面Tittle、版权信息',
        },
        {
          value: 'yxsz',
          label: '运行设置',
          icon: 'jeicon-run-setup',
          text: '系统模式、日志开关、权限开关、其他开关...',
        },
        {
          value: 'dlfw',
          label: '登录服务',
          icon: 'jeicon-login-service',
          text: '登录设定、登录方式、用户默认密码...',
        },
        {
          value: 'dsffw',
          label: '第三方服务',
          icon: 'jeicon-third-party',
          text: '微信登录、QQ登录、企业微信、微信公众平台...',
        },
        {
          value: 'xxfw',
          label: '消息服务',
          icon: 'jeicon-message',
          text: '调试、短信发送方式、短信配置信息、邮箱服务器...',
        },
        {
          value: 'wdgl',
          label: '文档管理',
          icon: 'jeicon-document-attribute',
          text: '文库管理员、文件格式',
        },
        {
          value: 'gzfw',
          label: '工作服务',
          icon: 'jeicon-work2',
          text: '工作日、节假日、工作时间',
        },
      ],
      formdata: Object.assign({}, form.defaultFormData),
      dictlist: {
        YESORNO: [],
        JE_SYSMODE: [],
        JE_WF_SUBMITTYPE: [],
        JE_CORE_SERVERRUN: [],
        JE_CORE_VERIFY: [],
        JE_CORE_NOTETYPE: [],
        JE_SYS_DOCFILETYPE: [],
        JE_CALENDAR_WEEK: [],
        JE_CALENDAR_FESTIVAL: [],
        JE_CALENDAR_HOURS: [],
        JE_CHILDREN_LAYOUT: [],
        JE_CORE_PUSH_PLATFORM: [],
      },
      checkItem: form.checkboxItems(),
      str2json: form.str2json(),
      str2list: form.str2list(),
      datePicker: form.datePicker(),
      hiddenItem: form.hiddenItem(),
    };
  },
  watch: {
    showDialog: {
      handler(nv, ov) {
        if (nv) {
          JE.setWestMenuVisible(false);
        } else {
          JE.setWestMenuVisible(true);
        }
      },
      immediate: true,
    },
  },
  created() {
    this.active = this.navlist[0];
    // this.formdata = Object.assign({}, form.defaultFormData);
    this.initData();
    this.searchDict();
  },
  mounted() {
  },
  methods: {
    initData() {
      loadSysVariables().then((data) => {
        // this.formdata = Object.assign({}, data.obj);// 处理页面逻辑用的data
        for (const key in form.defaultFormData) {
          // 该字段只走默认值
          if (key == 'JE_SYS_ENCRYPT_FIELD') {
            this.formdata[key] = form.defaultFormData[key];
          } else {
            this.formdata[key] = data.obj[key] || form.defaultFormData[key];
          }
        }
        for (const key in this.formdata) {
          // 处理checkbox：1 -> true, 0 -> false
          if (this.checkItem.indexOf(key) > -1) {
            if (this.formdata[key] === '1') {
              this.formdata[key] = true;
            } else if (this.formdata[key] === '0') {
              this.formdata[key] = false;
            }
          }
          // 处理列表转json
          if (this.str2json.indexOf(key) > -1) {
            this.formdata[key] = JSON.parse(this.formdata[key]);
          }
          // 字符串转数组
          if (this.str2list.indexOf(key) > -1) {
            this.formdata[key] = this.formdata[key].split(',');
          }
          // 节假日
          if (this.datePicker.indexOf(key) > -1) {
            this.formdata[key] = this.changeDateType(this.formdata[key]);
          }
        }
      });
    },
    async submit() {
      let params = {};
      let allFields = '';
      // 获取子组件的data值
      for (const key in this.$refs.formPage.$refs) {
        params = Object.assign({}, params, this.$refs.formPage.$refs[key].data);
      }
      // 获取 allFields
      for (const key in params) {
        allFields += `${key},`;
      }
      allFields += this.hiddenItem;
      params.allFields = allFields;
      // 将隐藏项添加到params
      const hiddenList = this.hiddenItem.split(',');
      hiddenList.forEach((item) => {
        // params[item] = this.formdata[item];
        params[item] = this.formdata[item] || form.defaultFormData[item];
      });
      for (const key in params) {
        // 处理checkbox：true -> 1, false -> 0
        if (this.checkItem.indexOf(key) > -1 && key != 'JE_SYS_ADMIN') {
          params[key] = params[key] ? '1' : '0';
        }
        // 处理列表转json
        if (this.str2json.indexOf(key) > -1) {
          params[key] = JSON.stringify(params[key]);
          params[key] = this.cn2code(params[key]);
        }
        // 字符串转数组
        if (this.str2list.indexOf(key) > -1) {
          params[key] = params[key].toString();
        }
        // 节假日
        if (this.datePicker.indexOf(key) > -1) {
          params[key] = JSON.parse(params[key]);
          params[key].forEach((item, index) => {
            const obj = {};
            obj.code = params[key][index].code;
            obj.text = params[key][index].text;
            obj.value = params[key][index].value;
            params[key][index] = obj;
          });
          params[key] = JSON.stringify(params[key]);
          params[key] = this.cn2code(params[key]);
        }
        if (key == 'JE_PUSH_CONFIG') {
          const obj = {};
          const arrayData = params[key];
          for (let index = 0; index < arrayData.length; index++) {
            const keyCode = arrayData[index].code;
            obj[keyCode] = arrayData[index].value;
          }
          params[key] = JSON.stringify(obj);
        }
      }
      const res = await writeSysVariables(params);
      if (res.success) {
        JE.msg('保存成功!');
      } else {
        JE.msg('保存失败!');
      }
    },
    searchDict() {
      for (const key in this.dictlist) {
        const params = {
          tableCode: 'JE_CORE_DICTIONARY',
          DICTIONARY_DDCODE: key,
          DICTIONARY_ZWFFLAG: '0',
        };
        getDicItemByCode(params).then((data) => {
          if (key == 'JE_CORE_PUSH_PLATFORM') {
            let numIdenx = 0;
            for (let index = 0; index < data.length; index++) {
              if (data[index].code == 'COMMON') {
                numIdenx = index;
              }
            }
            data.splice(numIdenx, 1);
          }
          this.dictlist[key] = data;
        });
      }
    },
    showForm(item) {
      this.active = item;
      this.showDialog = !this.showDialog;
      setTimeout(() => {
        this.$refs.formPage.changeNav(item);
      }, 50);
    },
    hideDialog() {
      this.showDialog = !this.showDialog;
    },
    changeDateType(list) {
      if (list.length < 1) {
        return [];
      }
      list.forEach((item, index) => {
        item.list = this.bubbleList(item.value);
        const limit = [];
        limit[0] = new Date(`${new Date().getFullYear()}-${item.list[0].replace(/-/g, '/')}`);
        limit[1] = new Date(`${new Date().getFullYear()}-${item.list[item.list.length - 1].replace(/-/g, '/')}`);
        this.$set(list[index], 'limit', limit);
      });
      return list;
    },
    bubbleList(arr) {
      const list = arr.split(',');
      let i = list.length - 1;
      while (i > 0) {
        let pos = 0;
        for (let j = 0; j < i; j += 1) {
          if (list[j] > list[j + 1]) {
            pos = j;
            // eslint-disable-next-line
            const tmp = list[j]; list[j] = list[j + 1]; list[j + 1] = tmp;
          }
        }
        i = pos;
      }
      return list;
    },
    cn2code(arr) {
      for (let i = 0; i < arr.length; i++) {
        if (/[\u4e00-\u9fa5]/.test(arr[i])) {
          const code = `\\u${arr[i].charCodeAt(0).toString(16)}`;
          arr = arr.replace(arr[i], code);
        }
      }
      return arr;
    },
  },
};
</script>

<style lang="scss" scoped>
  .page__syssetting {
    padding: 5% 2.5%;
    .entry_items {
      margin: 2.5%;
      width: 25%;
      height: 150px;
      padding: 20px;
      padding-left: 100px;
      position: relative;
      border: 1px solid transparent;
      .icon {
        position: absolute;
        top: 50%;
        left: 15%;
        transform: translate(-50%, -50%);
        font-size: 35px;
        color: #386bd0;
      }
      .text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        > p {
          font-size: 20px;
          &.title {
            font-size: 16px;;
          }
        }
      }
      &:hover {
        border: 1px solid #dddddd;
        box-shadow: 0 0 16px 0px rgba(0,0,0,0.14);
      }
    }
  }
</style>
<style lang="scss" scoped>
  .left {
    float: left;
  }
  .right {
    float: right;
  }
  .clearBoth {
    &:after {
      content: '';
      clear: both;
      display: table;
    }
  }
  .pointer {
    cursor: pointer;
  }
</style>

<style lang="scss">
  .sys_setting_dialog {
    .el-dialog {
      overflow: hidden;
      .el-dialog__header {
        display: none;
      }
      .el-dialog__body {
        padding: 0;
      }
    }
  }
</style>
